#!/bin/sh
# the next line restarts using wish \
exec wish "$0" ${1+"$@"}

# Loader --
# Simple Tk script for loading propeller with propeller-load.exe
# Click the Load button to load a binary program.
# Click the Quit button to exit.

package require Tk

proc getResult { result } {
    set output ""
    foreach item $result {
        if {[regexp "Ver" $item]} {
            append output $item "\n"
        }
        if {[regexp "sent" $item]} {
            append output $item "\n"
        }
    }
    return $output
}

button .load -text "Load" -command {
    set types [list]
    lappend types "typeName .binary"
    lappend types "typeName .eeprom"
    set file [tk_getOpenFile -filetypes $types]
    set err 0

    if { [regexp ".binary" $file]} {
        set loaddst "RAM"
        set loadopt "-r"
    } elseif { [regexp ".eeprom" $file] } {
        set loaddst "EEPROM"
        set loadopt "-e"
    } elseif { [regexp ".elf" $file] } {
        set loaddst "ELF to BINARY"
        set loadopt "-s"
    } else {
        puts "File must be type .binary, .eeprom, or .elf";
        set err 1
    }

    if {0 == $err} {
        set status 0
        if {[catch {exec -ignorestderr ./propeller-load $loadopt $file} result options]} {
            set result [split $result "\n"]
            tk_messageBox -message "Error loading $file\n\n[lindex $result 0]"
        } else {
            set result [split $result "\n"]
            set output [getResult $result]
            tk_messageBox -message "$file Loaded to $loaddst\n\n$output"
        }
    }
}
button .quit -text "Quit" -command {
    destroy .
}

label .name -text "Propeller Program Loader" -justify left
label .help -text "Load a Propeller .binary or .eeprom file." -justify left
label .pad  -text " " -width 20

grid .help -padx 8 -pady 10 -row 1 -column 1 -columnspan 4
grid .pad  -padx 8 -pady 10 -row 2 -column 1
grid .pad  -padx 8 -pady 10 -row 2 -column 2
grid .load -padx 8 -pady 10 -row 2 -column 3
grid .quit -padx 8 -pady 10 -row 2 -column 4

#wm iconbitmap . -default "Loader.ico"
wm title . "Propeller Loader"

# End:
